import { useState, useEffect, useRef } from "react"
import { useSearchParams } from "react-router-dom"
// comps
import FullLoading from "../../components/FullLoading"
import TopSided from "./components/TopSided"
import LeftSided from "./components/LeftSided"
import RightSided from "./components/RightSided"
// hook
// api
import { getProfessionalReport } from "../../request/api"
// utils

const ProfessionalPortrait = () => {
  // 处理页面宽高比
  const [scale, setScale] = useState(1)
  useEffect(() => {
    function adjustScale() {
      const baseWidth = 1920 // 设计稿基准宽度
      const currentWidth = window.innerWidth
      const scale = currentWidth / baseWidth
      setScale(scale)
      if (scale >= 1) return

      document.body.style.transform = `scale(${scale})`
      document.body.style.transformOrigin = "top left"
      document.body.style.width = `${baseWidth}px`
      document.body.style.height = `1080px`
    }

    window.addEventListener("resize", adjustScale)
    adjustScale() // 初始化
  }, [])

  const [searchParams] = useSearchParams()
  const title = searchParams.get("companyName")

  // fetch
  const [loading, setLoading] = useState(true)
  const didInit = useRef(false)
  const [data, setData] = useState({})

  useEffect(() => {
    const fn = async () => {
      if (!didInit.current) {
        didInit.current = true
        try {
          const companyName = decodeURIComponent(
            searchParams.get("companyName") || "国网武汉供电公司"
          )
          const { data } = await getProfessionalReport(companyName)
          setData(data)
          setLoading(false)
        } catch (error) {
          console.log("error: ", error)
          setLoading(false)
        }
      }
    }
    fn()
  }, [searchParams])

  return loading ? (
    <FullLoading />
  ) : (
    <div
      className="h-full relative"
      style={{
        backgroundImage: `url('assistant-decision_bg.png')`,
        backgroundRepeat: "no-repeat",
        backgroundSize: `${scale} ${scale}`
      }}
    >
      <TopSided />
      <main className="flex items-center justify-center px-[48px]">
        <div
          className="absolute top-0 bottom-0 left-0 w-[38px]"
          style={{
            backgroundImage: `url('assistant-decision/left-side.png')`,
            backgroundRepeat: "no-repeat",
            backgroundSize: "cover"
          }}
        ></div>
        <div
          className="absolute top-0 bottom-0 right-0 w-[38px]"
          style={{
            backgroundImage: `url('assistant-decision/right-side.png')`,
            backgroundRepeat: "no-repeat",
            backgroundSize: "cover"
          }}
        ></div>
        <LeftSided title={title} />
        <RightSided data={data} title={title} />
      </main>
    </div>
  )
}

export default ProfessionalPortrait
